/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dressingsocial.controller;

import com.dressingsocial.model.Opinion;
import com.dressingsocial.model.User;
import com.dressingsocial.model.Vote;
import com.dressingsocial.repository.OpinionRepository;
import com.dressingsocial.service.DressingService;
import com.dressingsocial.service.OpinionService;
import com.dressingsocial.service.UserService;
import com.dressingsocial.service.VoteService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author hayate
 */
@Controller
@RequestMapping(value = "/opinions/{id}/votes")
public class VoteController {

    @Autowired
    VoteService voteService;

    @Autowired
    OpinionRepository opinionRepository;

    @Autowired
    UserService userService;

    private User currentUser() {
        return userService.findById(new Long(1));
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String postVote(@PathVariable Long id) {
        Vote vote = new Vote();
        
        Opinion opinion = opinionRepository.findOne(id);
        vote.setOpinion(opinion); 
        Subject subject = SecurityUtils.getSubject();
        if(subject.isRemembered() || subject.isAuthenticated()){
            String email = (String)subject.getPrincipal();
            User user = userService.findByEmail(email);
            vote.setUser(user);
            voteService.create(vote);
            return "success";
        } else {
            return "failure";
        }
    }
    
    @RequestMapping(method = RequestMethod.GET)
    public String createVote(@PathVariable Long id) {
        Vote vote = null;
        Opinion opinion = opinionRepository.findOne(id);
        if (opinion != null) {
            vote = new Vote();
            vote.setOpinion(opinion);
            vote.setUser(currentUser());
            voteService.create(vote);

        }
        return "redirect:http://www.baidu.com/";

    }
}
